package com.ruoyi.business.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.ruoyi.business.Vo.DefinitionDetailVo;
import com.ruoyi.business.service.IProcessDifinitionService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.DefinitionDetail;
import com.ruoyi.business.service.IDefinitionDetailService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 流程定义明细Controller
 * 
 * @author shuangwaiwai
 * @date 2021-10-13
 */
@Controller
@RequestMapping("/business/detail")
public class DefinitionDetailController extends BaseController
{
    private String prefix = "business/detail";

    @Autowired
    private IDefinitionDetailService definitionDetailService;
    @Autowired
    private IProcessDifinitionService processDifinitionService;


    @RequiresPermissions("business:detail:view")
    @GetMapping("/{definitionInfoId}")
    public String detail(@PathVariable("definitionInfoId") Long definitionInfoId,ModelMap modelMap)
    {
        modelMap.addAttribute("definitionInfoId",definitionInfoId);
        return prefix + "/detail";
    }

    /**
     * 查询流程定义明细列表
     */
    @RequiresPermissions("business:detail:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(DefinitionDetail definitionDetail)
    {
        startPage();
        List<DefinitionDetailVo> list = definitionDetailService.selectDefinitionDetailList(definitionDetail);
        return getDataTable(list);
    }

    /**
     * 导出流程定义明细列表
     */
    @RequiresPermissions("business:detail:export")
    @Log(title = "流程定义明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(DefinitionDetail definitionDetail)
    {
        List<DefinitionDetailVo> list = definitionDetailService.selectDefinitionDetailList(definitionDetail);
        ExcelUtil<DefinitionDetailVo> util = new ExcelUtil<>(DefinitionDetailVo.class);
        return util.exportExcel(list, "流程定义明细数据");
    }
    /**
     * 部署
     */
    @RequiresPermissions("business:detail:deploy")
    @Log(title = "流程明细部署", businessType = BusinessType.EXPORT)
    @PostMapping("/deploy")
    @ResponseBody
    public AjaxResult deploy(MultipartFile processDefinition,Long definitionInfoId)
    {
        if(processDefinition==null) {
            return error("请选择要部署的文件！");
        }
        if(definitionInfoId==null) {
            return error("请选择流程定义再部署！");
        }
        String originalFilename = processDefinition.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        if(!(extension.equals("zip") || extension.equals("bpmn"))) {
            return error("文件类型只能是zip或bpmn！");
        }
        try {
            //上传文件到服务器
            String uploadPath = RuoYiConfig.getUploadPath();
            String filePath = FileUploadUtils.upload(uploadPath, processDefinition);

            //真实文件路径
            String realPath = RuoYiConfig.getProfile()+ filePath.substring(Constants.RESOURCE_PREFIX.length());

            //部署（部署流程图到工作流，新增一条部署记录）
            definitionDetailService.deployProcessDefinition(realPath,definitionInfoId);
        } catch (Exception e) {
            return error("部署流程失败，请联系管理员");
        }
        return success("部署成功！");
    }

    /**
     * 新增保存流程定义明细
     */
    @RequiresPermissions("business:detail:readResource")
    @Log(title = "流程文件查询", businessType = BusinessType.OTHER)
    @RequestMapping("/readResource")
    @ResponseBody
    public void readResource(Long deploymentId, String type, HttpServletResponse resp) throws IOException {
        InputStream inputStream = null;
        if("xml".equals(type)) {
            inputStream = processDifinitionService.getProcessDefinitionFileByDeploymentId(deploymentId);
        } else {
            inputStream = processDifinitionService.getProcessDefinitionImageByDeploymentId(deploymentId);
        }

        if(inputStream!=null) {
            IOUtils.copy(inputStream,resp.getOutputStream());
        }

    }


    /**
     * 新增流程定义明细
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存流程定义明细
     */
    @RequiresPermissions("business:detail:add")
    @Log(title = "流程定义明细", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(DefinitionDetail definitionDetail)
    {
        return toAjax(definitionDetailService.insertDefinitionDetail(definitionDetail));
    }

    /**
     * 修改流程定义明细
     */
    @GetMapping("/edit/{definitionInfoId}")
    public String edit(@PathVariable("definitionInfoId") Long definitionInfoId, ModelMap mmap)
    {
        DefinitionDetail definitionDetail = definitionDetailService.selectDefinitionDetailById(definitionInfoId);
        mmap.put("definitionDetail", definitionDetail);
        return prefix + "/edit";
    }

    /**
     * 修改保存流程定义明细
     */
    @RequiresPermissions("business:detail:edit")
    @Log(title = "流程定义明细", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(DefinitionDetail definitionDetail)
    {
        return toAjax(definitionDetailService.updateDefinitionDetail(definitionDetail));
    }

    /**
     * 删除流程定义明细
     */
    @RequiresPermissions("business:detail:remove")
    @Log(title = "流程定义明细", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(definitionDetailService.deleteDefinitionDetailByIds(ids));
    }
}
